using FI.BatchJob.Web.Data;
using FI.BatchJob.Web.Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using System;
namespace FI.BatchJob.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
              .MinimumLevel.Information()
              .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
              .Enrich.FromLogContext()
              .WriteTo.Console()
              .WriteTo.File(@"Logs/log.txt",
                  fileSizeLimitBytes: 1_000_000,
                  rollOnFileSizeLimit: true,
                  retainedFileCountLimit: 15,
                  shared: true,
                  flushToDiskInterval: TimeSpan.FromSeconds(1))
              .CreateLogger();

            try
            {
                Log.Information("Starting web host");

                var host = CreateWebHostBuilder(args).Build();

                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;
                    try
                    {
                        using (var context = services.GetService<ApplicationDbContext>())
                        {
                            context.Database.Migrate();

                            var userManager = services.GetService<UserManager<IdentityUser>>();
                            var roleManager = services.GetService<RoleManager<IdentityRole>>();

                            InitDataTool initData = new InitDataTool(userManager, roleManager, context);

                            initData.EnsureSeedData();

                        }


                    }
                    catch (Exception ex)
                    {
                        var logger = services.GetRequiredService<ILogger<Program>>();
                        logger.LogError(ex, "An error occurred while seeding the database.");
                    }
                }

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");

            }
            finally
            {
                Log.CloseAndFlush();
            }


        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
           WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .UseSerilog();

    }
}
